// 获取渠道参数
function getUrlParam(name) {
  //构造一个含有目标参数的正则表达式对象
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  //匹配目标参数
  var r = window.location.search.substr(1).match(reg);
  //返回参数值
  if (r != null) {
    return decodeURI(r[2]);
  }
  return null;
}

// 获取手机号码
function getPhoneInputNumber() {
  return document.getElementById("phone-input").value;
}

// 微信APP
const WXMpAppId = "wx4caa10223d09c719";
const hostDev = "http://127.0.0.1:8080"; // DEV
const hostWang = "https://wwapi.gxmgx.com"; // WANG
const hostRx = "https://rx.api.gxmgx.com"; // RX

const linkAppId = "wx6b12ec19746dec22";
const linkContent = "pages/index/index/c=test";

// 注册提交
function registerSubmit() {
  fetch(
    `${hostRx}/channel/register?channelName=${getUrlParam(
      "cn"
    )}&phoneNumber=${getPhoneInputNumber()}`,
    {
      method: "POST",
    }
  )
    .then((resp) => {
      resp
        .json()
        .then((json) => {
          console.log(json);
          const isAndroid = navigator.userAgent.indexOf("Android") > -1;
          if (isAndroid) {
            switch (json.androidInstallChannel) {
              case "Appstore": {
                return alert("暂不支持安装");
              }
              case "Distribute": {
                return (location.href = json.androidDistribute);
              }
              case "Sideloading": {
                return (location.href = json.androidInstallationPackage);
              }
            }
          } else {
            switch (json.iosinstallChannel) {
              case "Appstore": {
                return (location.href = json.iosappstoreUrlScheme);
              }
              case "Distribute": {
                return (location.href = json.iosdistribute);
              }
              case "CorporateSignature": {
                return (location.href = json.iosenterpriseUrlScheme);
              }
            }
          }
        })
        .catch((err) => {
          console.log(err);
        });
    })
    .catch((err) => {
      console.log(err);
    });
}

window.onload = () => {
  document.getElementById("submit").addEventListener("click", () => {
    if (!getPhoneInputNumber()) {
      return alert("请输入手机号");
    }

    if (getPhoneInputNumber().length !== 11) {
      return alert("请输入正确的手机号");
    }

    registerSubmit();
  });

  if (isWeiXinBrowser()) {
    // 微信标签,检查是否在微信浏览器内
    const wxTagCssPath = getUrlParam("wx-tag-css-path") || "wx-tag.css";

    const warpLogin = document.createElement("div");
    warpLogin.style.position = "relative";
    const warpLoginAbs = document.createElement("div");
    warpLoginAbs.style.position = "absolute";
    warpLoginAbs.style.top = 0;
    warpLoginAbs.style.left = 0;
    warpLoginAbs.style.zIndex = 999;
    warpLoginAbs.style.width = "100%";
    warpLoginAbs.style.height = "100%";
    warpLoginAbs.onclick = () => {
      alert(1);
    };

    document.getElementById("phone-input").addEventListener("change", (v) => {
      if (v.value.length === 11) {
        warpLogin.removeChild(warpLoginAbs);
      } else {
        warpLogin.appendChild(warpLoginAbs);
      }
    });

    const parent = document.getElementById("submit");

    // 微信标签,检查是否在微信浏览器内
    const wxOpenLaunchWeApp = document.createElement("wx-open-launch-weapp");

    wxOpenLaunchWeApp.addEventListener("launch", function (e) {
      console.log("success", e);
      addApply(jsonData.hireId)
        .then((res) => {
          console.log("addApply wx-applet success", res);
        })
        .catch((err) => {
          console.error(err);
        });
    });
    wxOpenLaunchWeApp.addEventListener("error", function (e) {
      console.log("fail", e);
    });

    wxOpenLaunchWeApp.setAttribute("appid", linkAppId);
    wxOpenLaunchWeApp.setAttribute("path", linkContent);

    const wxOpenLaunchWeAppScript = document.createElement("script");
    wxOpenLaunchWeAppScript.type = "text/wxtag-template";
    wxOpenLaunchWeAppScript.appendChild(el);

    if (wxTagCssPath) {
      fetch(wxTagCssPath).then((res) => {
        res.text().then((value) => {
          const style = document.createElement("style");
          style.innerHTML = value;
          wxOpenLaunchWeAppScript.appendChild(style);
        });
      });
    }

    wxOpenLaunchWeApp.appendChild(wxOpenLaunchWeAppScript);
    warpLogin.appendChild(wxOpenLaunchWeApp);
    parent.appendChild(warpLogin);
  }
};

/**
 * 申请记录查询
 */
function createJsapiSignature() {
  return new Promise((resolve, reject) => {
    fetch(
      hostWang +
        `/wx/mp/${WXMpAppId}/create-js_api-signature?${Qs.stringify({
          url: location.href,
        })}`
    )
      .then((res) => {
        if (res.status !== 200) {
          res
            .json()
            .then((json) => {
              reject(json);
            })
            .catch(reject);
        } else {
          res
            .json()
            .then((json) => {
              resolve(json);
            })
            .catch(reject);
        }
      })
      .catch(reject);
  });
}

// 自动注册微信页面
window.addEventListener("load", () => {
  // 是否微信浏览器
  function isWeiXinBrowser() {
    var ua = navigator.userAgent.toLowerCase();
    if (ua.indexOf("micromessenger") != -1) {
      return true;
    } else {
      return false;
    }
  }

  if (isWeiXinBrowser()) {
    const script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "https://res.wx.qq.com/open/js/jweixin-1.6.0.js";
    document.body.appendChild(script);

    document.addEventListener("WeixinOpenTagsError", function (e) {
      console.error(e.detail.errMsg);
      alert("微信版本过低,请升级到最新版");
    });

    script.addEventListener("load", () => {
      // when the js execute done
      wx.error(function (res) {
        console.error("config error", res);
      });

      const scriptQs = document.createElement("script");
      scriptQs.type = "text/javascript";
      scriptQs.src = "https://gitee.com/fellw/distribute-av1/raw/master/qs.min.js";
      document.body.appendChild(scriptQs);
      script.addEventListener("load", () => {
        createJsapiSignature().then((res) => {
          wx.config({
            ...res,
            debug: false,
            openTagList: ["wx-open-launch-weapp"],
            jsApiList: [], // 必填，需要使用的JS接口列表
          });
        });
      });
    });
  }
});
